<script setup lang="ts">
import { computed, onMounted } from "vue";
import { usageRate } from "@/utils/math";
import { formatNumberText } from "@/utils/cell";
import { useTradeStore } from "@/store/modules/tradeStore";
import { storeToRefs } from "pinia";

defineOptions({
  name: "account-stat"
});
const trade = useTradeStore();
const { apps, isLoadingApps, accountInfo } = storeToRefs(useTradeStore());

// writable computed
const selectedAppKeyModel = computed({
  get: () => trade.selectedAppKey,
  set: value => trade.setSelectedAppByKey(value)
});

const usageRateText = computed(() => {
  const bal = accountInfo.value?.account?.balance || 0;
  const ava = accountInfo.value?.account?.available || 0;
  const rate = usageRate(bal, ava);
  if (!Number.isFinite(rate) || rate < 0) return "-";
  return `${Math.round(rate)}%`;
});

const accountStatItems = computed(() => [
  {
    key: "balance",
    label: "权益",
    text:
      formatNumberText(accountInfo.value?.account?.balance, {
        digits: 0,
        separated: true
      }) || "-"
  },
  {
    key: "available",
    label: "可用",
    text:
      formatNumberText(accountInfo.value?.account?.available, {
        digits: 0,
        separated: true
      }) || "-"
  },
  { key: "usage", label: "使用率", text: usageRateText.value || "-" }
]);

onMounted(() => {
  trade.fetchApps();
});
</script>

<template>
  <div
    name="account-title"
    class="flex flex-col gap-2 border-b border-gray-100 px-3 py-2"
  >
    <div class="flex-bc gap-3">
      <el-select
        v-model="selectedAppKeyModel"
        :loading="isLoadingApps"
        placeholder="请选择账户"
        class="max-w-2/3 font-bold"
        clearable
      >
        <el-option
          v-for="item in apps"
          :key="`${item.trade_app_name}|${item.gateway_name}`"
          :label="item.account_name"
          :value="`${item.trade_app_name}|${item.gateway_name}`"
        />
      </el-select>
      <div class="text-sm text-gray-400">
        {{ accountInfo?.account_id }}
      </div>
    </div>
    <div class="flex-bc mt-1 gap-2 text-xs">
      <div v-for="item in accountStatItems" :key="item.key" class="flex">
        <span class="mx-1 text-gray-500">{{ item.label }}</span>
        <span class="text-md font-mono font-medium">{{ item.text }}</span>
      </div>
    </div>
  </div>
</template>
